package net

import (
	"github.com/kataras/iris/v12"
	"strconv"
)

type HttpRouter struct {
	Path   string
	Method string
	Handle func(ctx Context)
}

func (r *HttpRouter) runHandle(ctx Context) {
	if r.Handle != nil {
		r.Handle(ctx)
	}
}

type AppHttp struct {
	addr string
	app  *iris.Application
}

func (a *AppHttp) RegisterRouter(routers ...RouterInterface) {
	for _, router := range routers {
		if r, suc := router.(*HttpRouter); suc {
			a.app.Handle(r.Method, r.Path, func(c iris.Context) {
				r.runHandle(newContext(c))
			})
		}
	}
}

func newContext(c iris.Context) Context {
	token := c.GetHeader("token")
	uid, _ := strconv.ParseUint(c.GetHeader("uid"), 10, 64)
	return Context{
		Context: c,
		token:   token,
		uid:     uid,
	}
}

func NewHttp(addr string) *AppHttp {
	return &AppHttp{
		addr: addr,
		app:  iris.New(),
	}
}

func (a *AppHttp) Cors() {
	a.app.Use(func(ctx iris.Context) {
		ctx.Header("Access-Control-Allow-Origin", "*")
		if ctx.Request().Method == "OPTIONS" {
			ctx.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS")
			ctx.Header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization")
			ctx.StatusCode(204)
			return
		}
		ctx.Next()
	})

}

func (a *AppHttp) AddRouter(path, method string, handle func(ctx Context)) {
	a.app.Handle(method, path, func(c iris.Context) {
		handle(newContext(c))
	})
}

func (a *AppHttp) AddParty(patten string, auth func(ctx Context), handles ...func(p iris.Party)) {
	a.app.PartyFunc(patten, func(p iris.Party) {
		if auth != nil {
			p.Use(func(ctx iris.Context) {
				c := newContext(ctx)
				auth(c)
			})
		}
		for _, h := range handles {
			h(p)
		}
	})
}

func (a *AppHttp) Start() error {
	return a.app.Run(iris.Addr(a.addr))
}
